package com.zhengsr.corelib.net;

import android.support.annotation.Nullable;


import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink;

/**
 * Created by zhengshaorui
 * Time on 2018/8/15
 * 监听requestbody的传递，用来表示上传进度
 */

public class ContentRequestBody extends RequestBody {
    private RequestBody mRequestBody;

    private ContentRequestBody(RequestBody requestBody){
        mRequestBody = requestBody;

    }

    public static ContentRequestBody create(RequestBody requestBody){
        return new ContentRequestBody(requestBody);
    }

    @Override
    public long contentLength() throws IOException {
        return mRequestBody.contentLength();
    }

    @Nullable
    @Override
    public MediaType contentType() {
        return mRequestBody == null ? null:mRequestBody.contentType();
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        CountSink countSink = new CountSink(sink);

        BufferedSink bufferedSink = Okio.buffer(countSink);
        mRequestBody.writeTo(bufferedSink);
        bufferedSink.flush();
    }

    protected final class CountSink extends ForwardingSink {
        private long sum;
        public CountSink(Sink delegate) {
            super(delegate);
        }

        @Override
        public void write(Buffer source, long byteCount) throws IOException {
            super.write(source, byteCount);
            sum += byteCount;
            // Log.d(TAG, "write: "+sum+" / "+contentLength());

        }
    }
}
